import Router from 'koa-router'
import { Models } from '../../../../common/typings/model'
import httpErrors from '../../../../core/HttpException'
import Mysql from '../../../../core/Mysql'
import Auth from '../../../../middlewares/Auth'
import validator from '../../../../middlewares/validator'
import addComponent from '../../../../common/apiValidate/lowCode/component/addComponent'
import DateUtils from '../../../../common/utils/DateUtils'

const router = new Router({
  prefix: '/api/v1/lowCode/component',
})

/*
 * 新增看板
 * @return
 */
router.post(
  '/addComponent',
  Auth.verifyTokenPermission,
  validator(addComponent, 'body'),
  async (ctx: Models.Ctx, next) => {
    const { name, parentId, chartAxisData, chartStyle, chartType } = ctx.request.body
    const userId = ctx.auth.uid
    const date = DateUtils.format(new Date())
    const res = await Mysql.command(`
    INSERT INTO component ( name, parent_id, chart_axis_data, chart_style, chart_type, created_user_id,  created_at, updated_at )
          VALUES
          ( '${name}', ${parentId}, '${chartAxisData}', '${chartStyle}', ${chartType} ${userId} ,'${date}', '${date}' );
    SELECT
      b.id,
      b.name,
      b.parent_id,
      b.updated_at,
      u.user_name created_user
    FROM
      component b,
      user u
    WHERE
      b.id = (SELECT LAST_INSERT_ID())
    AND
      u.id = b.created_user_id

  `)
    throw new httpErrors.Success(res.results[1][0])
  }
)

export default router
